package com.softa.utils;

import com.alibaba.fastjson.JSONObject;
import com.softa.bean.Result;
import com.softa.enummodel.ResponseErrorEnum;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

public class ResponseUtil {

	/**
	 * 返回错误 处理
	 * 
	 * @param response
	 * @param responseString
	 * @throws IOException
	 */
	public static void responseErrors(HttpServletResponse response,
			String responseString, ResponseErrorEnum errorType)
			throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JSONObject.toJSONString(new Result(Result.ResultStatus.Fail.ordinal(), errorType.getErrorTypeKey(), responseString)));
		out.close();
	}

	public static void responseSuccess(HttpServletResponse response,
			String responseString) throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JSONObject.toJSONString(new Result(Result.ResultStatus.SUCCESS.ordinal(), responseString)));
		out.close();
	}

	public static void responseSuccess(HttpServletResponse response,
			Object data, String responseString) throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JSONObject.toJSONString(new Result(Result.ResultStatus.SUCCESS.ordinal(), responseString, data)));
		out.close();
	}

	/**
	 * 返回错误 处理
	 * 
	 * @param response
	 * @param responseString
	 * @throws IOException
	 */
	public static void responseError(HttpServletResponse response,
			String responseString, ResponseErrorEnum errorType)
			throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JSONObject.toJSONString(new Result(Result.ResultStatus.Fail.ordinal(), errorType.getErrorTypeKey(), responseString)));
		out.close();
	}

	public static void responseError(HttpServletResponse response,
			String[] responseString, ResponseErrorEnum errorType)
			throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Set<String> errSet = new HashSet<String>();
		if (responseString != null) {
			for (String err : responseString) {
				errSet.add(err);
			}
		}
		out.write(JSONObject.toJSONString(new Result(Result.ResultStatus.SUCCESS.ordinal(), errorType.getErrorTypeKey(), errSet)));
		out.close();
	}
}
